package com.toolboxkit.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 线程操作工具类
 * 提供线程管理、线程池操作等常用功能
 */
public class ThreadUtils {
    
    /**
     * 创建固定大小的线程池
     *
     * @param size 线程池大小
     * @return ExecutorService线程池实例
     */
    public static ExecutorService createFixedThreadPool(int size) {
        return Executors.newFixedThreadPool(size);
    }
    
    /**
     * 创建单线程线程池
     *
     * @return ExecutorService线程池实例
     */
    public static ExecutorService createSingleThreadExecutor() {
        return Executors.newSingleThreadExecutor();
    }
    
    /**
     * 创建缓存线程池
     *
     * @return ExecutorService线程池实例
     */
    public static ExecutorService createCachedThreadPool() {
        return Executors.newCachedThreadPool();
    }
    
    /**
     * 安全地关闭线程池
     *
     * @param executorService 要关闭的线程池
     */
    public static void shutdown(ExecutorService executorService) {
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
    }
    
    /**
     * 立即关闭线程池，中断正在执行的任务
     *
     * @param executorService 要关闭的线程池
     */
    public static void shutdownNow(ExecutorService executorService) {
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdownNow();
        }
    }
    
    /**
     * 等待线程池终止
     *
     * @param executorService 要等待的线程池
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return 是否成功终止
     * @throws InterruptedException 如果等待过程中被中断
     */
    public static boolean awaitTermination(ExecutorService executorService, long timeout, TimeUnit unit) 
            throws InterruptedException {
        if (executorService != null) {
            return executorService.awaitTermination(timeout, unit);
        }
        return true;
    }
    
    /**
     * 当前线程睡眠指定毫秒数
     *
     * @param millis 睡眠毫秒数
     */
    public static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    /**
     * 创建守护线程
     *
     * @param runnable 线程执行的任务
     * @param name 线程名称
     * @return 守护线程
     */
    public static Thread createDaemonThread(Runnable runnable, String name) {
        Thread thread = new Thread(runnable, name);
        thread.setDaemon(true);
        return thread;
    }
}